<script setup lang="ts">
import * as echarts from 'echarts'
import { fa, tr } from 'element-plus/es/locale';
import { onMounted, ref,onUnmounted } from 'vue'
setData

defineExpose({
  setData
})

// 组件传参
const props = defineProps({
  width: {
    type: String, //参数类型
    default: '100%', //默认值
    required: false //是否必须传递
  },
  height: {
    type: String,
    default: '10rem',
    required: true
  },
  option: {
    type: Object,
    default: () => {
      return {}
    },
    required: true
  },
  initBefore: {
    type: Function,
    required: false
  },
  initAfter: {
    type: Function,
    required: false
  }
})
const chartRef = ref<null | HTMLDivElement>(null);
// const used=ref(true)
let chartInstance: any;

//声明周期函数，自动执行初始化
onMounted(() => {
  init()
  window.addEventListener('resize', resize, false)
})

onUnmounted(()=>{
  chartInstance.dispose()
})

//初始化函数
function init() {
  if(chartRef.value){
    chartInstance=echarts.init(chartRef.value)
    chartInstance.setOption(props.option)
  }
}

function resize() {
  chartInstance.resize()
}
// 父组件可调用，设置动态数据
function setData(option: Record<string, any>) {
  chartInstance.setOption(option)
  if(props.initAfter){
    props.initAfter(chartInstance)
  }
}
</script>

<template>
  <div ref="chartRef" :style="`width: ${props.width} ; height: ${props.height}`" />
</template>

<style lang="scss" scoped></style>
